1/usr/bin/env python
import time
import smbus

#********************************************
# Custard Pi 7 resources v1.0 5th Dec 2013

#I2C addresses
#Set suitable address on Custard Pi 7

add0= 0x20
add1= 0x21
add2= 0x22
add3= 0x23
add4= 0x24
add5= 0x25
add6= 0x26
add7= 0x27

bus=smbus.SMBus(1)

#set IODIR register 
iodir= 0x00
#set bit 0 and bit 1 as inputs, the others as outputs
inout= 0x03
#set GPIO register
gpio= 0x09
#set output latch
olat=0x0A

#set output ON
ONoc4= 0x04
ONoc3= 0x08
ONoc2= 0x10
ONoc1= 0x20
ONrl2= 0x40
ONrl1= 0x80

#set output OFF
OFFoc4= 0xFB
OFFoc3= 0xF7
OFFoc2= 0xEF
OFFoc1= 0xDF
OFFrl2= 0xBF
OFFrl1= 0x7F

def setbit(address, byte):
    #sets selected port pin
    outstatus = bus.read_byte_data(address, olat) | byte
    bus.write_byte_data(address, gpio, outstatus)

def clrbit(address, byte):
    #clears selected port pin
    outstatus = bus.read_byte_data(address, olat) & byte
    bus.write_byte_data (address, gpio, outstatus)

def readbit(address, bit):
    #read status of bit 0 or 1
    bitvalue = bus.read_byte_data(address, gpio) & bit
    return bitvalue

def setinandout(address):            
    #set bit 0 and bit 1 as inputs, the others as outputs
    bus.write_byte_data(address, iodir, inout)

def alloff(address):
    #clear all relays
    bus.write_byte_data (address, gpio, 0x03)